<?php

namespace addons\cmstostatic\controller;

use think\addons\Controller;

class Index extends Controller
{

    public function index()
    {
        $this->error("当前插件暂无前台页面");
    }

    public function install(){
        $cmstostatic = new \addons\cmstostatic\Cmstostatic();
        $rs = $cmstostatic->importSqlData();

        if($rs){
            if($cmstostatic->install())
            {
                return '<h1 style="color: green;">恭喜，插件[cmstostatic]安装成功！</h1>';
            }
            else{
                return '<h1 style="color: red;">插件安装失败</h1>';
            }
        }
        else{
            return '<h1 style="color: red;">数据表创建失败</h1>';
        }
    }

    public function token_search()
    {
        $format = $this->request->param('format', 'js');

        $token_html = token('__searchtoken__');
        $token_str = substr($token_html, 51, -4);

        if('js' == $format){
            return 'document.write(\'' . $token_html . '\');';
        }
        elseif('text' == $format){
            return $token_str;
        }
        elseif('json' == $format){
            return json(['token'=>$token_str]);
        }
        elseif('html' == $format){
            return $token_html;
        }
        else{
            return $token_html;
        }
    }

    public function token_message()
    {
        $format = $this->request->param('format', 'js');

        $token_html = token();
        $token_str = substr($token_html, 45, -4);

        if('js' == $format){
            return 'document.write(\'' . $token_html . '\');';
        }
        elseif('text' == $format){
            return $token_str;
        }
        elseif('json' == $format){
            return json(['token'=>$token_str]);
        }
        elseif('html' == $format){
            return $token_html;
        }
        else{
            return $token_html;
        }
    }

    public function article_view()
    {
        $id = $this->request->param('id', 0, 'intval');
        $format = $this->request->param('format', 'js');

        $model = new \addons\cms\model\Archives;
        $Article = $model->find($id);

        // 给与默认值
        $views = mt_rand(134, 357);

        if($Article){
            $Article->setInc('views');
            $views = $Article->views;
        }

        if('js' == $format){
            return 'document.write(\'' . $views . '\');';
        }
        elseif('json' == $format){
            return json(['views'=>$views]);
        }
        else{
            return $views;
        }
    }
}
